package com.yubb.web.controller.platform;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yubb.common.annotation.PlatformLog;
import com.yubb.common.constant.Constants;
import com.yubb.common.constant.UserConstants;
import com.yubb.common.core.controller.BaseController;
import com.yubb.common.core.domain.AjaxResult;
import com.yubb.common.core.domain.Ztree;
import com.yubb.common.core.domain.platform.PlatformDept;
import com.yubb.common.core.domain.platform.PlatformUser;
import com.yubb.common.core.domain.platform.dto.PlatformDeptDTO;
import com.yubb.common.core.domain.platform.dto.PlatformRoleDTO;
import com.yubb.common.core.domain.platform.vo.PlatformDeptVO;
import com.yubb.common.enums.BusinessType;
import com.yubb.common.utils.ShiroUtils;
import com.yubb.common.utils.StringUtils;
import com.yubb.common.utils.bean.DozerUtils;
import com.yubb.platform.service.IPlatformDeptService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 *@Description 部门信息
 *@Author zhushuyong
 *@Date 2021/5/26 14:42
 *@since:
 *@copyright: 版权所有2021 开源组织 gitee(https://gitee.com/jinzheyi)作者：朱述勇<br/>
 *            GitHub(https://github.com/jinzheyi)作者：朱述勇 。
 */
@Controller
@RequestMapping("/platform/dept")
public class PlatformDeptController extends BaseController
{
    private String prefix = "platform/dept";

    @Autowired
    private IPlatformDeptService deptService;

    @RequiresPermissions("platform:dept:view")
    @GetMapping()
    public String dept(ModelMap mmap)
    {
        PlatformDept platformDept = deptService.getOne(new LambdaQueryWrapper<PlatformDept>()
                .eq(PlatformDept::getDeptType, Constants.YB));
        mmap.put("TOP_DEPT_ID", platformDept.getId());
        mmap.put("TOP_PARENT_ID", Constants.TOP_PARENT_DEPT_ID);
        return prefix + "/dept";
    }

    @RequiresPermissions("platform:dept:list")
    @PostMapping("/list")
    @ResponseBody
    public List<PlatformDeptVO> list(PlatformDeptDTO dept)
    {
        List<PlatformDeptVO> deptList = deptService.selectDeptList(dept);
        return deptList;
    }

    /**
     * 新增部门
     */
    @GetMapping("/add/{parentId}")
    public String add(@PathVariable("parentId") String parentId, ModelMap mmap)
    {
        if (!DozerUtils.copyProperties(ShiroUtils.getPlatformUser(), PlatformUser.class).isAdmin())
        {
            parentId = ShiroUtils.getPlatformUser().getDeptId();
        }
        mmap.put("dept", deptService.selectDeptById(parentId));
        return prefix + "/add";
    }

    /**
     * 新增保存部门
     */
    @PlatformLog(title = "部门管理", businessType = BusinessType.INSERT)
    @RequiresPermissions("platform:dept:add")
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@Validated PlatformDeptDTO dept)
    {
        if (UserConstants.DEPT_NAME_NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept)))
        {
            return error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        dept.setCreateBy(ShiroUtils.getPlatformUser().getLoginName());
        return toAjax(deptService.insertDept(dept));
    }

    /**
     * 修改
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap)
    {
        PlatformDeptVO dept = deptService.selectDeptById(id);
        PlatformDept platformDept = deptService.getOne(new LambdaQueryWrapper<PlatformDept>()
                .eq(PlatformDept::getDeptType, Constants.YB));
        if (StringUtils.isNotNull(dept) && platformDept.getId().equals(id))
        {
            dept.setParentName("无");
        }
        mmap.put("dept", dept);
        mmap.put("TOP_PARENT_ID", Constants.TOP_PARENT_DEPT_ID);
        return prefix + "/edit";
    }

    /**
     * 保存
     */
    @PlatformLog(title = "部门管理", businessType = BusinessType.UPDATE)
    @RequiresPermissions("platform:dept:edit")
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated PlatformDeptDTO dept)
    {
        if (UserConstants.DEPT_NAME_NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept)))
        {
            return error("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        else if (dept.getParentId().equals(dept.getId()))
        {
            return error("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        }
        else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus())
                && deptService.selectNormalChildrenDeptById(dept.getId()) > 0)
        {
            return AjaxResult.error("该部门包含未停用的子部门！");
        }
        dept.setUpdateBy(ShiroUtils.getPlatformUser().getLoginName());
        return toAjax(deptService.updateDept(dept));
    }

    /**
     * 删除
     */
    @PlatformLog(title = "部门管理", businessType = BusinessType.DELETE)
    @RequiresPermissions("platform:dept:remove")
    @GetMapping("/remove/{id}")
    @ResponseBody
    public AjaxResult remove(@PathVariable("id") String id)
    {
        if (deptService.selectDeptCount(id) > 0)
        {
            return AjaxResult.warn("存在下级部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(id))
        {
            return AjaxResult.warn("部门存在用户,不允许删除");
        }
        return toAjax(deptService.deleteDeptById(id));
    }

    /**
     * 校验部门名称
     */
    @PostMapping("/checkDeptNameUnique")
    @ResponseBody
    public String checkDeptNameUnique(PlatformDeptDTO dept)
    {
        return deptService.checkDeptNameUnique(dept);
    }

    /**
     * 选择部门树
     * 
     * @param id 部门ID
     * @param excludeId 排除ID
     */
    @GetMapping(value = { "/selectDeptTree/{id}", "/selectDeptTree/{id}/{excludeId}" })
    public String selectDeptTree(@PathVariable("id") String id,
            @PathVariable(value = "excludeId", required = false) String excludeId, ModelMap mmap)
    {
        mmap.put("dept", deptService.selectDeptById(id));
        mmap.put("excludeId", excludeId);
        return prefix + "/tree";
    }

    /**
     * 加载部门列表树
     */
    @GetMapping("/treeData")
    @ResponseBody
    public List<Ztree> treeData()
    {
        List<Ztree> ztrees = deptService.selectDeptTree(new PlatformDeptDTO());
        return ztrees;
    }

    /**
     * 加载部门列表树（排除下级）
     */
    @GetMapping("/treeData/{excludeId}")
    @ResponseBody
    public List<Ztree> treeDataExcludeChild(@PathVariable(value = "excludeId", required = false) String excludeId)
    {
        PlatformDeptDTO dept = new PlatformDeptDTO();
        dept.setId(excludeId);
        List<Ztree> ztrees = deptService.selectDeptTreeExcludeChild(dept);
        return ztrees;
    }

    /**
     * 加载角色部门（数据权限）列表树
     */
    @GetMapping("/roleDeptTreeData")
    @ResponseBody
    public List<Ztree> deptTreeData(PlatformRoleDTO role)
    {
        List<Ztree> ztrees = deptService.roleDeptTreeData(role);
        return ztrees;
    }
}
